<template>
  <div class="container">
    <transition :name="routerAni">
      <router-view @selectPersonCb="selectPersonCb" class="router-view of-y-s"></router-view>
    </transition>
    <print-bill v-if="showPrint" :k2Data="k2Data" @hidePrint="hidePrint"></print-bill>
    <div class="w-p100 h-p100 of-y-s">
      <div class="base-content">
        <div @click="showTpl = true" class="line box box-ac tpl">
          <div class="box-f1">
            <div class="">选择模板</div>
            <div class="box input">{{checkedTpl ? checkedTpl.TemplateName : '选择模板'}}</div>
          </div>
          <div class="icon-arrow-right icon"></div>
        </div>
        <div class="line box box-ac">
          <div class="box-f1">
            <div class="">发起人</div>
            <div class="box input">{{userInfo.userName}}</div>
          </div>
        </div>
        <div class="line box box-ac copy">
          <div @click="selectPerson(1)" class="box-f1">
            <div class="">抄送</div>
            <div class="input box">
              <div v-if="CCPosition.length === 0" >添加抄送</div>
              <div :value="item" :key="index" v-for="(item, index) in CCPosition" class="item">
                <div class="name">{{item.name}}</div>
                <div @click.stop="deletePerson(index)" class="icon icon-close"></div>
              </div>
            </div>
          </div>
          <div class="icon-arrow-right icon"></div>
        </div>
      </div>
      <div class="tag">常用选择</div>
      <draggable v-model="checkedTpl.ActivitiesInfo" :options="{draggable:'.node-item', handle: '.icon-qiehuan'}" v-if="checkedTpl && checkedTpl.ActivitiesInfo" class="node-list">
        <div :value="item" :key="index" v-for="(item, index) in checkedTpl.ActivitiesInfo" class="node-item box box-ac">
          <div class="icon icon-qiehuan"></div>
          <div class="box box-f1 box-ver">
            <div v-if="!item.IsCanEdit" class="title box box-ac">{{item.ActivityName}}</div>
            <input v-if="item.IsCanEdit" class="title box box-ac" v-model="item.ActivityName" type="text">
            <div @click="selectPerson(2, index)" class="user box box-ac tc-999" >{{item.ActivityDestsInfo[0].K2UserName ? item.ActivityDestsInfo[0].K2UserName : '请选择审批人'}}</div>
          </div>
          <div @click="deleteNode(index)" v-if="item.IsCanEdit" class="icon icon-del"></div>
        </div>
      </draggable>
      <div @click="addNode()" class="add box box-ac box-jc">
        +添加节点
      </div>
      <div @click="sendK2()" class="btn submit box box-ac box-jc">提交</div>
      <div @click="showTpl = false" v-if="templateInfos && showTpl" class="tpl-container">
        <div @click.stop class="content box box-ver animated slideInUp">
          <div @click="checkTpl(item)" :value="item" :key="index" v-for="(item, index) in templateInfos" class="item">
            {{item.TemplateName}}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import store from '@/store'
import { formatDate } from '@/assets/js/filters'
import printBill from '@/components/printBill'
import { getJMByBillNum } from '@/assets/js/common'
import draggable from 'vuedraggable'

export default {
  name: 'sendK2',
  components: {
    printBill,
    draggable
  },
  data () {
    return {
      k2Data: {},
      templateInfos: null,
      checkedTpl: null, // 选择的模板
      showTpl: false,
      process: null,
      CCPosition: [], // 抄送人
      showPrint: false,
      K2COM: ''
    }
  },
  computed: mapState(['userNum', 'userInfo', 'bizAccountBill', 'routerAni']),
  created () {
    let k2Data = sessionStorage.getItem('k2Data')
    if (!k2Data) return this.$router.replace('/')
    this.k2Data = JSON.parse(k2Data)
    this.K2COM = this.userInfo.companyNum
    // console.log('k2Data>>>', this.k2Data)
    this.getK2COM(K2COM => {
      this.K2COM = K2COM
      this.getProcessInfoForEAS()
    })
    // this.getProcessInfoForEAS()
    // this.getK2COM()
  },
  methods: {
    // 发起K2
    sendK2 () {
      if (!this.process) {
        this.$tools.openToast({
          msg: '获取流程失败',
          duration: 2000
        })
        return
      }

      if (!this.checkedTpl) {
        this.$tools.openToast({
          msg: '请先选择模板',
          duration: 2000
        })
        return
      }

      let process = this.process
      let templateInfoJson
      let myProcessHeadJson
      let CCPositionIDs = []
      let CCPositionNames = []
      let ActivitiesInfo = []
      let sCreateTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      // 是否每个节点都选择了审批人
      let ActivitiesInfoIsOk = true
      this.checkedTpl.ActivitiesInfo.forEach(item => {
        if (!item.ActivityDestsInfo[0].K2UserID) {
          ActivitiesInfoIsOk = false
        }
        ActivitiesInfo.push(item)
      })

      if (!ActivitiesInfoIsOk) {
        this.$tools.openToast({
          msg: '存在未选择审批人的节点',
          duration: 2000
        })
        return
      }

      // 抄送人
      this.CCPosition.forEach(item => {
        CCPositionIDs.push(item.number)
        CCPositionNames.push(item.name)
      })
      CCPositionNames = CCPositionIDs.join(';')
      CCPositionIDs = CCPositionIDs.join(';')
      // if (CCPositionIDs.length === 0) {
      //   CCPositionIDs = ''
      //   CCPositionNames = ''
      // } else {

      // }
      myProcessHeadJson = {
        sCompany: '', // 公司:如：szzb
        sDeptmentID: '',
        sDeptmentName: '',
        sProjectID: '',
        sProjectName: '',
        sPriority: this.process.ProcessProperty, // 优先级 如：0：高  1：普通
        sOriginator: this.userInfo.userNum, // 发起人：如：VANKE\v-heyongj
        sCreateTime, // 创建时间,不能为空
        sProcessFolder: this.process.ProcessType, // 流程分类
        sProcessSubject: this.k2Data.sProcessSubject, // 流程主题,不能为空
        sProcInstNO: '', // 流程编号
        sCapital: this.k2Data.sCapital, // 金额 数字类型,不能为空 如果有金额就需要传递金额
        sEndCCUserID: CCPositionIDs, // 抄送人ID
        sEndCCUserName: CCPositionNames // 抄送人名称
      }

      templateInfoJson = this.checkedTpl
      templateInfoJson.FastnessCCUserID = CCPositionIDs
      templateInfoJson.FastnessCCUser = CCPositionNames
      templateInfoJson.ActivitiesInfo = ActivitiesInfo

      let requestData

      // 出差申请和出差报销
      if (this.k2Data.BOID) {
        let bodysJson = [
          {
            sKey: 'amount',
            sValue: this.k2Data.sCapital
          },
          {
            sKey: 'url',
            sValue: this.k2Data.bodysJson
          },
          {
            sKey: 'costedDept',
            sValue: this.userInfo.depNum
          },
          {
            sKey: 'type',
            sValue: this.k2Data.barcodeType
          },
          {
            sKey: 'barcode',
            sValue: this.k2Data.barcode
          }]

        requestData = {
          method: 'startK2process',
          number: this.k2Data.billNum,
          BSID: this.k2Data.BSID,
          BOID: this.k2Data.BOID,
          processID: this.process.ProcessID,
          bodysJson: JSON.stringify(bodysJson),
          myProcessHeadJson: JSON.stringify(myProcessHeadJson),
          templateInfoJson: JSON.stringify(templateInfoJson),
          filelistJson: ''

          // billNum: this.k2Data.billNum,
          // strBSID: this.k2Data.BSID,
          // processID: this.process.ProcessID,
          // myProcessHeadJson: JSON.stringify(myProcessHeadJson),
          // templateInfoJson: JSON.stringify(templateInfoJson),
          // filelistJson: '',
          // userNum: this.userNum
        }
      } else {
        requestData = {
          method: 'startK2ForEAS',
          billNum: this.k2Data.billNum,
          strBSID: this.k2Data.BSID,
          processID: this.process.ProcessID,
          myProcessHeadJson: JSON.stringify(myProcessHeadJson),
          templateInfoJson: JSON.stringify(templateInfoJson),
          filelistJson: '',
          userNum: this.userNum
        }
      }

      this.$http({
        url: this.$config.api.host,
        method: 'post',
        data: requestData
      }).then(res => {
        if (res.code === 200) {
          this.$store.commit('bizAccountBill', {
            state: 145
          })
          // 带发票的费报 差报 需要打印封面
          let JM = getJMByBillNum(this.k2Data.billNum)
          if ((JM === 'FB' && !this.k2Data.iseinvoice) || JM === 'CB20') {
            this.showPrint = true
          } else {
            this.$tools.openToast({
              msg: '发起成功',
              duration: 2000
            })
            setTimeout(() => {
              this.hidePrint()
            }, 1500)
          }
        }
      })
    },
    hidePrint (status) {
      this.showPrint = false
      this.$store.commit('resetBizAccountBill')
      this.$router.replace('/')
    },
    deletePerson (index) {
      this.CCPosition.splice(index, 1)
    },
    // 选择模板
    checkTpl (checkedTpl) {
      this.showTpl = false
      this.checkedTpl = JSON.parse(JSON.stringify(checkedTpl))
    },
    // 选择审批人
    selectPerson (type, index) {
      console.log(`选择人员  type:${type} | index:${index}`)
      this.$router.push({
        path: '/sendK2/k2PersonSelect',
        query: {
          type,
          index
        }
      })
    },
    selectPersonCb (item) {
      console.log('选择的人>>>', item)
      if (+item.type === 1) {
        let isRepeat = false
        let length = this.CCPosition.length
        for (let i = 0; i < length; i++) {
          if (this.CCPosition[i].number === item.number) {
            isRepeat = true
            break
          }
        }
        if (!isRepeat) this.CCPosition.push(item)
      } else {
        this.checkedTpl.ActivitiesInfo[item.index].ActivityDestsInfo[0].UserID = item.number
        this.checkedTpl.ActivitiesInfo[item.index].ActivityDestsInfo[0].UserName = item.name
        this.checkedTpl.ActivitiesInfo[item.index].ActivityDestsInfo[0].K2UserID = item.number
        this.checkedTpl.ActivitiesInfo[item.index].ActivityDestsInfo[0].K2UserName = item.name
      }
    },
    deleteNode (index) {
      this.checkedTpl.ActivitiesInfo.splice(index, 1)
    },
    addNode () {
      if (!this.checkedTpl) {
        this.$tools.openToast({
          msg: '请先选择模板信息',
          duration: 2000
        })
        return
      }
      let newNode = this.initNode({
        name: '',
        number: ''
      })
      this.checkedTpl.ActivitiesInfo.push(newNode)
    },
    // 添加审批节点
    initNode (item) {
      let { name, number } = item
      let ActivityDestsInfo = {
        ProcInstID: 0,
        ActivityID: 0,
        UserID: number,
        UserName: name,
        K2UserID: number,
        K2UserName: name,
        TemplateType: 1,
        ActivityDestID: 0,
        CCUserID: '',
        CCUserName: '',
        PositionID: '',
        PositionName: '',
        CCPositionID: '',
        CCPositionName: '',
        Position_UserID: null,
        Topic: null,
        SysID: '',
        SysName: ''
      }
      let newActivitiesInfo = {
        ActivityApproval: '&',
        ActivityDestsInfo: [ActivityDestsInfo],
        ActivityID: 0,
        ActivityIgnore: '',
        ActivityK2Name: '可选步骤',
        ActivityMessage: '',
        ActivityName: '审批人',
        ActivityOrder: 1,
        ActivityRemark: '()',
        ApproveInfo: '',
        ApproveLimit: '',
        AutomaticApproval: true,
        CanSelectStep: [],
        CanSelectStep2: '',
        ExpiredDays: 0,
        IdeaModel: '',
        IsCloseActivity: false,
        IsEmail: true,
        IsEndCC: false,
        IsCanEdit: true, // 单独添加的参数 控制节点名字是否可编辑
        IsFastnessActivity: false, // 是否删除 true:不能删除
        IsFastnessUser: false, // 能否修改审批人 true:不能修改
        IsLCS: false,
        IsMultiple: false,
        IsMultipleApproval: false,
        IsSMS: false,
        MultipleApprovalMax: null,
        PositionName: '',
        ProcessActivityID: 0,
        ShowDisAgree: true,
        ShowReturn: true,
        TemplateID: 0, // 模板id
        TemplateType: 1
      }
      return newActivitiesInfo
    },
    // 获取模板信息
    getProcessInfoForEAS () {
      this.$http({
        url: this.$config.api.K2Url + 'GetProcessInfoForEAS',
        data: {
          BSID: this.k2Data.BSID, // 业务类型
          Company: this.K2COM, // 公司ID
          ExpenseType: this.k2Data.ExpenseType ? this.k2Data.ExpenseType : this.k2Data.BSID, // 费用 类型  电脑两个单的费用类型就是渠道ID
          myProcessHeadJson: `{"sOriginator":${this.userNum}}`,
          bodysJson: ''
        }
      }).then(res => {
        if (res.templateInfos && res.process) {
          console.log('模板信息获取成功')
          this.templateInfos = res.templateInfos
          this.process = res.process
        } else {
          this.$tools.openToast({
            msg: '获取模板信息失败',
            duration: 2000
          })
        }
      })
    },
    // 获取发起K2所需公司编码
    getK2COM (cb) {
      console.log(this.k2Data)
      this.$http({
        url: this.$config.api.host,
        data: {
          method: 'getK2COM',
          BILLNMUBER: this.k2Data.billNum, // 业务类型
          BSID: this.k2Data.BSID
        }
      }).then(res => {
        if (res.code === 200) cb(res.K2COM)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config';
@import '../assets/css/mixins';
.base-content{
  margin-top:.25rem;
  background-color:#FFF;
  padding: 0 .3rem;
}
.line{
  padding:.2rem 0;
  border-top:1px solid $borderColor;
  font-size:.32rem;
  &:nth-of-type(1){
    border:none;
  }
  .input{
    font-size:.28rem;
    margin-top:.1rem;
    color:#999;
  }
}
.copy{
  .item{
    background-color:#ebf7ff;
    color:#666;
    border-radius:.15rem;
    padding:0.05rem .15rem;
    position:relative;
    margin-right:.2rem;
  }
}
.icon-qiehuan{
  width:.64rem;
  height:.64rem;
  margin-right:.3rem;
  @include bg-image('../assets/images/icon-qiehuan');
}
.node-list{
  .node-item{
    margin-bottom: .2rem;
    background-color:#FFF;
    padding:0 .3rem;
    position: relative;
    .title,.user{
      height:1rem;
    }
    .title{
      border-bottom:1px solid $borderColor;
    }
    .icon-del{
      position:absolute;
      top:.3rem;
      right:.3rem;
      width:.3rem;
      height:.32rem;
      @include bg-image('../assets/images/icon-del');
    }
  }
}
.icon-close{
  width:.3rem;
  height:.3rem;
  background-color:#FFF;
  border-radius: 50%;
  position:absolute;
  right:-.15rem;
  top:-.15rem;
  @include bg-image('../assets/images/icon-close');
}
.tag{
  color:#999;
  font-size:.28rem;
  padding:.2rem .3rem;
}
.add{
  background-color:#FFF;
  height:1rem;
  color:#333;
  font-size:.32rem;
  margin-bottom:1.2rem;
}
.submit{
  position: fixed;
  bottom:0;
  background-color:$themeColor;
  color:#FFF;
  font-size:.32rem;
  width:100%;
  height:1rem;
}

.tpl-container{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  z-index:2;
  background-color: rgba(0,0,0,.5);
  .content{
    position:absolute;
    background-color: #FFF;
    bottom:0;
    left:0;
    width:100%;
    .item{
      width:100%;
      font-size:.32rem;
      padding:.3rem 0;
      border-top:1px solid $borderColor;
      color:#333;
      text-align: center;
      &:nth-of-type(1){
        border:none;
      }
    }
  }
}
</style>
